//
//  WmcClassifyAlbumDetailVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/5/18.
//

import MJRefresh
import UIKit

// MARK: - 扩展WmcClassifyAlbumDetailVC + WmcNavigatorProtocol

extension WmcClassifyAlbumDetailVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.allPhoto]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcClassifyAlbumDetailVM()

        if let viewModel = parms.context as? WmcClassifyAlbumDetailVM {
            vm = viewModel
        }

        let vc = WmcClassifyAlbumDetailVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcClassifyAlbumDetailVC + WmcVMProtocol

extension WmcClassifyAlbumDetailVC: WmcVMProtocol {
    typealias VMType = WmcClassifyAlbumDetailVM
}

// MARK: - [WmcClassifyAlbumDetailVC]

class WmcClassifyAlbumDetailVC: WmcBaseVC, WmcAlbumTransitionProtocol {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        title = viewModel.title

        fetchData()
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "我的云相册"

        navView.addSubview(shareBtn)

        if viewModel.type == .allPhoto {
            addSubview(searchView)
            searchView.addSubview(searchIconView)
            searchView.addSubview(searchLabel)
        }
        addSubview(collectionView)
        addSubview(badNetworkView)

        collectionView.addSubview(emptyView)

        shareBtn.snp.makeConstraints { make in
            make.centerY.equalTo(navView.backImageView)
            make.right.equalTo(-Wmc_standardEdge.right)
        }

        if viewModel.type == .allPhoto {
            searchView.snp.makeConstraints { make in
                make.left.equalTo(16)
                make.right.equalTo(-16)
                make.top.equalTo(navView.snp.bottom).offset(10)
                make.height.equalTo(48)
            }

            searchIconView.snp.makeConstraints { make in
                make.left.equalTo(16)
                make.centerY.equalToSuperview()
                make.width.height.equalTo(18)
            }

            searchLabel.snp.makeConstraints { make in
                make.left.equalTo(searchIconView.snp.right).offset(4)
                make.right.equalTo(-16)
                make.top.bottom.equalToSuperview()
            }

            collectionView.snp.makeConstraints { make in
                make.top.equalTo(searchView.snp.bottom).offset(24)
                make.left.right.bottom.equalToSuperview()
            }
        } else {
            collectionView.snp.makeConstraints { make in
                make.top.equalTo(navView.snp.bottom).offset(10)
                make.left.right.bottom.equalToSuperview()
            }
        }

        emptyView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }

        badNetworkView.snp.makeConstraints { make in
            make.edges.equalTo(collectionView)
        }

        var isShowedGuide: Bool = false
        if let isShowed: Bool = WmcUserdefault.object(forKey: .Tips.CloudAlbum.shareBubbles) {
            isShowedGuide = isShowed
        }

        if !isShowedGuide {
            self.showTakePhotoBubble()
        }
    }

    override func bindViewAction() {
        shareBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            WmcUserdefault.save(value: true, forKey: .Tips.CloudAlbum.shareBubbles)
            weakSelf.bubbleView?.dismiss()
            WmcHudManager.loading()
            weakSelf.viewModel.fetchShare { model in
                WmcHudManager.dismiss()
                if model.url.isEmpty {
                    WmcHudManager.toast("分享失败")
                    return
                }

                let shareAlertView = WmcShareAlertView()
                let sharedConfig: WmcShareAlertView.ShareType.Config = .init(title: model.title,
                                                                             description: model.content,
                                                                             thumbImage: UIImage.YP.AppIcon)
                shareAlertView.shareType =
                    .link(model.url, config: sharedConfig)
                let height = Wmc_safeAreaBottom + 214
                let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(height)
                }))
                presentVC.show()

            } failure: { error in
                WmcHudManager.dismiss()
                if let error = error {
                    WmcHudManager.toast(error)
                } else {
                    WmcHudManager.toast("网络请求失败")
                }
            }
        }

        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: false)
        })

        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadMore()
        })

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        searchView.isUserInteractionEnabled = true
        searchView.addGestureRecognizer(tap)

        bubbleView?.closeClosure = {
            WmcUserdefault.save(value: true, forKey: .Tips.CloudAlbum.shareBubbles)
        }

        NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumDataDidChange(notification:)), name: NSNotification.Name(rawValue: "com.watermark.classifyAlbumDataDidChange"), object: nil)
    }

    @objc
    func photoAlbumDataDidChange(notification: Notification) {
        self.fetchData(showLoading: true)
    }

    override func bindViewModel() {
        badNetworkView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: true)
        }
    }

    func deleteMedia(index: Int, vm: WmcMediaBrowseVM) {
        vm.presentDeleteAlert { [weak self] in
            guard let weakSelf = self else { return }
            var indexPath: IndexPath?
            var indexTemp: Int = 0
            for (sectionIndex, section) in weakSelf.viewModel.dataSource.enumerated() {
                for (rowIndex, _) in section.list.enumerated() {
                    if indexTemp == index {
                        indexPath = IndexPath(row: rowIndex, section: sectionIndex)
                        break
                    }
                    indexTemp += 1
                }
                if indexPath != nil {
                    break
                }
            }
            if let indexPath = indexPath {
                WmcHudManager.loading()
                weakSelf.viewModel.deleteImage(indexPath: indexPath, index: index) {
                    WmcHudManager.dismiss()
                    WmcHudManager.toast("删除成功")
                    NotificationCenter.default.post(name: NSNotification.Name("com.watermark.classifyAlbumDataDidChange"), object: self, userInfo: nil)

                    vm.remove(at: index)

                    if weakSelf.viewModel.dataSource.isEmpty {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            weakSelf.fetchData(showLoading: true)
                        }
                    } else {
                        weakSelf.collectionView.reloadData()
                    }
                } failure: { error in
                    WmcHudManager.toast("删除失败")
                    WmcHudManager.dismiss()
                }
            }
        }
    }

    // Private

    private lazy var shareBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "分享", image: "share".wmc_image)
        btn.setTintColor(.wmc_mainTheme)
        btn.font = 16.wmc_font
        btn.imgSize = 20.wmc_autoHor
        return btn
    }()

    private var bubbleView: WmcBubbleView?

    private lazy var searchView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH20_F7F7F7
        view.layer.cornerRadius = 4
        return view
    }()

    private lazy var searchIconView: UIImageView = {
        let view = UIImageView(image: "search".wmc_image.yp.set(tintColor: UIColor.wmc_grayH11_9D9DB3))
        return view
    }()

    private lazy var searchLabel: UILabel = {
        let label = UILabel()
        label.font = 16.wmc_font
        label.textColor = .wmc_grayH11_9D9DB3
        label.text = "查找图片"
        return label
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 38) / 3.0
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        layout.sectionHeadersPinToVisibleBounds = false

        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudPhotoCell.self, forCellWithReuseIdentifier: "WmcCloudPhotoCell")
        collectView.register(WmcCloudAllPhotoCollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "WmcCloudAllPhotoCollectionHeaderView")
        return collectView
    }()

    private lazy var emptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        view.isHidden = true
        return view
    }()

    private lazy var badNetworkView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.isHidden = true
        return view
    }()

    private func showTakePhotoBubble() {
        let title = "照片可以批量分享了"
        let config = WmcBubbleVM.ContentStyle.TextConfig(textColor: .wmc_white_FFFFFF, font: 18.wmc_font, textAlignment: .center)

        let bubbleVM = WmcBubbleVM()
        bubbleVM.contentStyle = .text(title, config: config)
        bubbleVM.closeType = .close
        bubbleVM.closeStyle = .line
        bubbleVM.useCloseBtn = true
        bubbleVM.bubbleSize = CGSize(width: 220, height: 44)
        bubbleVM.contentCornerRadius = 8
        bubbleVM.markView = shareBtn
        bubbleVM.showInView = view
        bubbleVM.showDirection = .bottom
        bubbleVM.markViewCenterOffset = -80
        bubbleVM.arrowOffset = -bubbleVM.markViewCenterOffset
        bubbleView = WmcBubbleView(bubbleVM)
        bubbleView?.show()
    }

    /// 移除气泡
    private func hideTakePhotoBubble() {
//        bubbleView.dismiss()
    }

    @objc
    private func tapAction() {
        WmcNavigatorManager.push(.cloudScreenPhoto)
    }

    private func fetchData(showLoading: Bool = true) {
        if showLoading {
            WmcHudManager.loading()
        }

        viewModel.refresh { [weak self] list in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.resetNoMoreData()
            }

            weakSelf.emptyView.isHidden = !list.isEmpty
            weakSelf.showRequestFailure(isShow: false)
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.mj_header?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")

            weakSelf.showRequestFailure(isShow: true)
        }
    }

    private func loadMore() {
        viewModel.loadMore { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.endRefreshing()
            }

            weakSelf.emptyView.isHidden = true
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_footer?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func showRequestFailure(isShow: Bool) {
        if viewModel.dataSource.isEmpty {
            collectionView.isHidden = isShow
            badNetworkView.isHidden = !isShow
        } else {
            badNetworkView.isHidden = true
            collectionView.isHidden = false
        }
    }

    private func pushPhotoBrowser(index: Int) {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = .backTitle(title: "云相册")
        browseVM.albumType = .cloud
        browseVM.showIndex = index
        browseVM.mediaList = viewModel.browserDataSource
        browseVM.backStyle = .right // 从右侧返回出
        browseVM.shareFriendsCircleMode = .custom
        browseVM.shareWechatMode = .custom

        browseVM.actionBlock = { [weak self] type, index, vm in
            guard let weakSelf = self else { return }
            switch type {
            case .delete:
                weakSelf.deleteMedia(index: index, vm: vm)
            case .save:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    wmcImage.loadUIImage() { image in
                        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                        if photoAlbumStatus.info.isAvailable {
                            UIImageWriteToSavedPhotosAlbum(image, self, #selector(weakSelf.saveImage(_:didFinishSaving:contextInfo:)), nil)
                        } else {
                            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                        }
                    }
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    switch wmcVideo.videoType {
                    case let .url(url):
                        let urlString = URL.YP.Create(url).yp.string
                        guard let keyWindow = UIApplication.shared.keyWindow else { return }
                        let progressBarView = WmcProgressBarView.showInView(keyWindow)

                        progressBarView.cancelClosure = {
                            WmcDownloadManager.shared.cancel()
                        }

                        WmcDownloadManager.shared.downloadFile(url: urlString) { value in
                            let progressText = String(format: "正在下载中%.2f", value * 100) + "%"
                            progressBarView.setProgress(Float(value), progressText: progressText)
                        } success: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("已保存到系统相册")
                        } failure: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("保存失败")
                        }
                    default: break
                    }
                }
            case .shareWechat:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .session)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .session)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            case .shareFriendsCircle:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .friendCircle)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .friendCircle)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            default: break
            }
        }
        let vc = WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
        vc?.hidesBottomBarWhenPushed = true
    }

    private func showShareView(_ shareAlertView: WmcShareAlertView) {
        let height = Wmc_safeAreaBottom + 214
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(height)
        }))
        presentVC.show()
    }

    private func shared(image: WmcImage?, scene: WmcShareManager.Scene) {
        guard let wmcImage = image else { return }
        wmcImage.loadUIImage { image in
            WmcShareManager.shareImage(image, scene: scene)
        }
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("已保存到系统相册")
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

extension WmcClassifyAlbumDetailVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let group = viewModel.dataSource.yp.object(at: section) {
            return group.list.count
        }
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudPhotoCell", for: indexPath) as! WmcCloudPhotoCell
        if let group = viewModel.dataSource.yp.object(at: indexPath.section),
           let model = group.list.yp.object(at: indexPath.row)
        {
            cell.bindModel(model)
        }
        return cell
    }

    // 设置 区头和区尾
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView: WmcCloudAllPhotoCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "WmcCloudAllPhotoCollectionHeaderView", for: indexPath) as! WmcCloudAllPhotoCollectionHeaderView
        if let group = viewModel.dataSource.yp.object(at: indexPath.section) {
            headerView.bindModel(group)
        }

        return headerView
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: self.view.bounds.width, height: 41)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: self.view.bounds.width, height: 0)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let _ = collectionView.cellForItem(at: indexPath) as? WmcCloudPhotoCell else { return }
        self.tabBarController?.tabBar.isHidden = true
        var index: Int?
        var indexTemp: Int = 0
        for (sectionIndex, section) in viewModel.dataSource.enumerated() {
            for (rowIndex, _) in section.list.enumerated() {
                if sectionIndex == indexPath.section, rowIndex == indexPath.row {
                    index = indexTemp
                    break
                }
                indexTemp += 1
            }
            if index != nil {
                break
            }
        }

        guard let index = index else {
            return
        }
        pushPhotoBrowser(index: index)
    }
}
